
var User = require('../models/user');
var Task = require('../models/task');
var TaskItem = require('../models/taskItem');
var moment = require('moment');
var _ = require('lodash');
var Helper = require('../lib/helper');
var fs = require('fs');
var thunkify = require('thunkify');
var unlink = thunkify(fs.unlink);
var readFile = thunkify(fs.readFile);
var exists = thunkify(fs.exists);

module.exports.index = function *(next){
  if(!Helper.isLogin(this)){
    return this.redirect('/admin/login');
  }

  var user_id = Helper.getLoginUID(this);

  var task = yield Task.where({'user_id':user_id}).sort({'date':-1,'_id':-1}).find();

  var task_tmp = [];

  var index = 0;
  var task_item;
  while(task_item = task[index]){
    task_item['list'] = yield TaskItem.where({'task_id':task_item.attributes._id}).find();
    task_tmp.push(task_item);
    index++;
  }

  //按月份分组
  var group_task = [];
  group_task = _.groupBy(task_tmp,function(n){
    return n.attributes.date;
  });
  yield this.render('admin/index',{'name':'Qeeniao','title':'任务后台','task':group_task});
};


module.exports.addManager = function *(next){
  var user = new User();
  user.set('email','huhongwei@qeeniao.com');
  user.set('password',Helper.passEncode('123456'));
  var res = yield user.save();
  if(res){
    return this.redirect('/admin');
  }
};


module.exports.downloadImageZip = function *(){
  if(!Helper.isLogin(this)){
    this.flash.error = '请登录后在进行操作';
    return this.redirect('/admin/login');
  }

  var args = this.params;
  if(!args.task_id){
    this.flash.error = '要下载的资源不存在!';
    return this.redirect('/admin');
  }

  var task = yield Task.where('_id',args.task_id).findOne();
  var task_item = yield TaskItem.where('task_id',task.attributes._id).sort({'_id':-1}).find();
  
  yield Helper.donwloadArchiveFile(task,task_item);
  var res = yield Helper.archive(task,task_item);
  yield Helper.deleteArchiveFile(task,task_item);

  if(res['success']){
    this.type = 'zip';
    this.attachment(task.attributes.name+'.zip');
    return this.body = yield Helper.readFile(res['path']);
  }

  this.body = '程序异常，请稍后再试';
  //this.type = 'zip';
  //this.body = yield Helper.readFile(upload_filename);

};

module.exports.login = function *(next){
  yield this.render('admin/login',{'title':'管理员登录'});
};

module.exports.doLogin = function *(next){
  var params = this.request.body;
  var email= params.email || '';
  var password = params.password || '';
  var Helper = require('../lib/helper');

  if(!email || !password){
    this.flash.error = '登录账号或登录密码不能为空！';
    return this.redirect('/admin/login');
  }

  var where = {'email':email,'password':Helper.passEncode(password)};
  var res = yield User.where(where).findOne();
  
  if(_.size(res)){
    this.session = {'login_qeeniao':{'login_on':true,'id':res.attributes._id}};
    return this.redirect('/admin');
  }else{
    this.flash.error = '登录账号或登录密码错误！';
    return this.redirect('/admin/login');
  }
};

module.exports.logout = function *(next){
  this.session = {'login_qeeniao':{'login_on':false}};
  return this.redirect('/admin/login');
};

/**
 * 导入页面
 * @yield {[type]} [description]
 */
module.exports.export = function *(){

  this.flash = {};
  yield this.render('admin/task/export',{'title':'导入文件生成任务'});
}

/**
 * 执行导入操作
 * @yield {[type]} [description]
 */
module.exports.doExport = function *(){
  var params = this.request.body;

  var xlsx = require('node-xlsx');
  var parse = require('co-busboy');
  var path = require('path');
  var fs = require('fs');
  var os = require('os');
  // multipart upload
  var parts = parse(this,{
    checkFile: function (fieldname, file, filename) {
      console.log('fieldname:',fieldname);
      if (path.extname(filename) !== '.xlsx') {
        var err = new Error('暂时不支持非xlsx格式的文件')
        err.status = 400
        return err
      }
    }
  });
  var part;
  var upload_res;
  var key = Helper.random();
  var filename = 'huanping_'+key+'.xlsx';
  var obj;
  try{
    while (part = yield parts) {

      console.log('part:',part);
      yield this.save(part,__dirname + '/../static/upload/'+filename);

      obj = xlsx.parse(__dirname + '/../static/upload/'+filename); // parses a file

      var name = '';
      var description = '';
      var demand = '';
      var memberName = [];
      var memberContent = [];
      if(_.size(obj) && _.has(obj[0],'data')){
        var i=0;
        var item;
        while(item = obj[0]['data'][i]){

          if(!_.size(item)){
            break;
          }

          if(i==0){
            name = item[0];
            i++;
            continue;
          }

          if(i==1){
            description = item[0]
            i++;
            continue;
          }

          if(i==2){
            demand = item[0];
            i++;
            continue;
          }

          memberName.push(item[0]);
          if(!_.isEmpty(item[1])){
            memberContent.push(item[1]);
          }else{
            memberContent.push('');
          }

          i++;
        }
      }

      var data = {};
      data['name'] = name;
      data['description'] = description;
      data['demand'] = demand;
      data['memberName'] = memberName;
      data['memberContent'] = memberContent;
      
      yield unlink(__dirname + '/../static/upload/'+filename);
    }
  }catch(error){
    this.throw(error);
  }
  

  this.body = {'success':true,'data':data};
}